/**
 * 同步执行监控页面
 * 显示同步任务的执行记录和实时状态
 */

import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Select,
  Row,
  Col,
  Tag,
  Progress,
  Tooltip,
  Modal,
  Typography,
  Statistic,
  Timeline,
  Alert,
  Descriptions
} from 'antd';
import type { TableColumnsType, TableProps } from 'antd';
import {
  ReloadOutlined,
  SearchOutlined,
  EyeOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  StopOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  DownloadOutlined
} from '@ant-design/icons';

import { useAuth } from '../contexts/AuthContext';
import { PermissionGuard } from '../components/PermissionGuard';
import { requestGuard } from '../utils/requestGuard';
import { syncApi } from '../services/syncApi';

import type {
  SyncExecution,
  SyncExecutionQueryParams,
  SyncLog
} from '../types/sync';
import {
  ExecutionType,
  ExecutionStatus,
  ExecutionStatusLabels,
  ExecutionTypeLabels,
  LogLevelLabels
} from '../types/sync';

const { Search } = Input;
const { Option } = Select;
const { Text, Title } = Typography;

const SyncExecutionMonitor: React.FC = () => {
  // 状态管理
  const [executions, setExecutions] = useState<SyncExecution[]>([]);
  const [logs, setLogs] = useState<SyncLog[]>([]);
  const [loading, setLoading] = useState(false);
  const [logsLoading, setLogsLoading] = useState(false);
  const [selectedExecution, setSelectedExecution] = useState<SyncExecution | null>(null);
  const [isLogsModalVisible, setIsLogsModalVisible] = useState(false);

  // 查询参数
  const [selectedTaskId, setSelectedTaskId] = useState<number | undefined>();
  const [selectedStatus, setSelectedStatus] = useState<ExecutionStatus | undefined>();

  // 分页参数
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) =>
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
  });

  // Hooks
  const { hasPermission } = useAuth();
  const isLoadingRef = useRef(false);
  const refreshInterval = useRef<NodeJS.Timeout>();

  // 权限检查
  const permissions = {
    canView: hasPermission('sync:execution:view'),
    canControl: hasPermission('sync:execution:control'),
  };

  /**
   * 获取执行记录列表
   */
  const fetchExecutions = useCallback(async (forceRefresh: boolean = false) => {
    const currentParams: SyncExecutionQueryParams = {
      page: pagination.current,
      page_size: pagination.pageSize,
      task_id: selectedTaskId,
      status: selectedStatus
    };

    // 使用requestGuard防止重复请求
    if (!forceRefresh && !requestGuard.canRequest('fetchExecutions', currentParams)) {
      return;
    }

    if (isLoadingRef.current) {
      return;
    }

    try {
      setLoading(true);
      isLoadingRef.current = true;

      const response = await syncApi.getSyncExecutions(currentParams);

      setExecutions(response.items);
      setPagination(prev => ({
        ...prev,
        total: response.total,
        current: response.page,
        pageSize: response.page_size
      }));

    } catch (error) {
      console.error('获取执行记录列表失败:', error);
    } finally {
      setLoading(false);
      isLoadingRef.current = false;
      requestGuard.completeRequest('fetchExecutions');
    }
  }, [pagination.current, pagination.pageSize, selectedTaskId, selectedStatus]);

  /**
   * 获取执行日志
   */
  const fetchLogs = useCallback(async (executionId: number) => {
    try {
      setLogsLoading(true);
      const response = await syncApi.getSyncLogs(executionId, {
        page: 1,
        page_size: 100
      });
      // 按创建时间倒序排列，最新的日志在前面
      const sortedLogs = (response.items || []).sort((a, b) =>
        new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      );
      setLogs(sortedLogs);
    } catch (error) {
      console.error('获取执行日志失败:', error);
    } finally {
      setLogsLoading(false);
    }
  }, []);

  /**
   * 暂停同步执行
   */
  const handlePauseExecution = useCallback(async (record: SyncExecution) => {
    try {
      await syncApi.pauseSyncExecution(record.id);
      // 刷新列表
      await fetchExecutions(true);
    } catch (error) {
      console.error('暂停同步执行失败:', error);
    }
  }, [fetchExecutions]);

  /**
   * 恢复同步执行
   */
  const handleResumeExecution = useCallback(async (record: SyncExecution) => {
    try {
      // 恢复就是移除暂停状态，让同步继续
      // 这里可以调用一个恢复API，或者重新执行任务
      // 暂时通过重新执行来实现恢复
      const { Modal } = await import('antd');

      Modal.confirm({
        title: '确认恢复',
        content: `确定要恢复执行记录 ID: ${record.id} 吗？`,
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          // 这里应该调用恢复API，暂时先提示用户
          const { message } = await import('antd');
          message.info('恢复功能正在开发中，请重新执行任务');
        }
      });
    } catch (error) {
      console.error('恢复同步执行失败:', error);
    }
  }, [fetchExecutions]);

  /**
   * 取消同步执行
   */
  const handleCancelExecution = useCallback(async (record: SyncExecution) => {
    try {
      // 显示确认对话框
      const { Modal } = await import('antd');

      Modal.confirm({
        title: '确认取消',
        content: `确定要取消执行记录 ID: ${record.id} 吗？此操作不可撤销。`,
        okText: '确定',
        cancelText: '取消',
        okType: 'danger',
        onOk: async () => {
          await syncApi.cancelSyncExecution(record.id);
          // 刷新列表
          await fetchExecutions(true);
        }
      });
    } catch (error) {
      console.error('取消同步执行失败:', error);
    }
  }, [fetchExecutions]);

  /**
   * 下载CSV文件
   */
  const handleDownloadCSV = useCallback(async (record: SyncExecution) => {
    try {
      // 动态导入所需组件
      const { Modal, Form, Select, Checkbox } = await import('antd');

      // 创建一个Promise来处理Modal的结果
      const showDownloadModal = () => {
        return new Promise<any>((resolve, reject) => {
          let formInstance: any;

          const modal = Modal.confirm({
            title: '下载CSV文件配置',
            width: 500,
            icon: null,
            content: (
              <Form
                ref={(form) => { formInstance = form; }}
                layout="vertical"
                initialValues={{
                  delimiter: ',',
                  quote_char: '"',
                  escape_special_chars: true,
                  encoding: 'utf-8'
                }}
              >
                <Form.Item name="delimiter" label="分隔符">
                  <Select>
                    <Select.Option value=",">逗号 (,)</Select.Option>
                    <Select.Option value="|">竖线 (|)</Select.Option>
                    <Select.Option value="\t">制表符 (Tab)</Select.Option>
                    <Select.Option value=";">分号 (;)</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="quote_char" label="引用字符">
                  <Select>
                    <Select.Option value='"'>双引号 (")</Select.Option>
                    <Select.Option value="'">单引号 (')</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="encoding" label="文件编码">
                  <Select>
                    <Select.Option value="utf-8">UTF-8</Select.Option>
                    <Select.Option value="gbk">GBK</Select.Option>
                    <Select.Option value="gb2312">GB2312</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item name="escape_special_chars" valuePropName="checked">
                  <Checkbox>处理特殊字符（换行、引号等）</Checkbox>
                </Form.Item>
              </Form>
            ),
            okText: '下载',
            cancelText: '取消',
            onOk: () => {
              if (formInstance) {
                const values = formInstance.getFieldsValue();
                resolve(values);
              } else {
                reject(new Error('表单实例未找到'));
              }
            },
            onCancel: () => {
              reject(new Error('用户取消'));
            }
          });
        });
      };

      // 显示配置对话框
      const csvConfig = await showDownloadModal();

      // 导入syncApi并下载
      const { default: syncApi } = await import('../services/syncApi');

      // 调用API下载文件，传递CSV参数
      const response = await syncApi.downloadExecutionCSV(record.id, csvConfig);

      // 获取文件内容
      const blob = await response.blob();

      // 从响应头中获取文件名，如果没有则使用默认名称
      const contentDisposition = response.headers.get('Content-Disposition');
      let filename = `execution_${record.id}_${new Date().toISOString().slice(0, 10)}.csv`;

      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename=(.+)/);
        if (filenameMatch) {
          filename = filenameMatch[1].replace(/"/g, '');
        }
      }

      // 创建临时链接进行下载
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      // 显示成功提示
      const { notification } = await import('antd');
      notification.success({
        message: '下载成功',
        description: `文件 ${filename} 已成功下载`,
        placement: 'topRight',
      });

    } catch (error) {
      if (error instanceof Error && error.message === '用户取消') {
        return; // 用户取消，不显示错误
      }

      console.error('下载CSV文件失败:', error);
      // 显示错误提示
      import('antd').then(({ notification }) => {
        notification.error({
          message: '下载失败',
          description: error instanceof Error ? error.message : '下载CSV文件时发生错误',
          placement: 'topRight',
        });
      });
    }
  }, []);

  /**
   * 触发数据获取的包装函数 - 避免useEffect依赖问题
   */
  const triggerDataFetch = useCallback(() => {
    fetchExecutions(true); // 强制刷新，绕过requestGuard
  }, [fetchExecutions]);

  /**
   * 初始化数据获取 - 只在组件挂载时执行一次，遵循其他管理页面的模式
   */
  useEffect(() => {
    if (!permissions.canView) return;

    // 清除可能存在的请求防护状态（页面刷新时）
    requestGuard.clearGuard('fetchExecutions');

    // 获取数据
    triggerDataFetch();
  }, [permissions.canView]); // 移除函数依赖，避免无限循环

  /**
   * 分页和搜索条件变化时获取数据
   */
  useEffect(() => {
    if (!permissions.canView) return;

    fetchExecutions();
  }, [permissions.canView, fetchExecutions]);

  // 自动刷新运行中的任务
  useEffect(() => {
    const hasRunningTasks = executions.some(exec => exec.status === ExecutionStatus.RUNNING);
    
    if (hasRunningTasks) {
      refreshInterval.current = setInterval(() => {
        fetchExecutions(true);
      }, 5000); // 每5秒刷新一次
    } else {
      if (refreshInterval.current) {
        clearInterval(refreshInterval.current);
      }
    }

    return () => {
      if (refreshInterval.current) {
        clearInterval(refreshInterval.current);
      }
    };
  }, [executions, fetchExecutions]);

  /**
   * 筛选处理
   */
  const handleFilterChange = useCallback((type: string, value: any) => {
    switch (type) {
      case 'taskId':
        setSelectedTaskId(value);
        break;
      case 'status':
        setSelectedStatus(value);
        break;
    }
    setPagination(prev => ({ ...prev, current: 1 }));
  }, []);

  /**
   * 表格变化处理
   */
  const handleTableChange: TableProps<SyncExecution>['onChange'] = (paginationConfig) => {
    setPagination(prev => ({
      ...prev,
      current: paginationConfig.current || 1,
      pageSize: paginationConfig.pageSize || 10,
    }));
  };

  /**
   * 查看日志
   */
  const handleViewLogs = (execution: SyncExecution) => {
    setSelectedExecution(execution);
    setIsLogsModalVisible(true);
    fetchLogs(execution.id);
  };

  /**
   * 关闭日志模态框
   */
  const closeLogsModal = () => {
    setIsLogsModalVisible(false);
    setSelectedExecution(null);
    setLogs([]);
  };

  /**
   * 获取执行状态标签
   */
  const getExecutionStatusTag = (status: ExecutionStatus) => {
    const statusConfig = {
      pending: { color: 'default', icon: <ClockCircleOutlined /> },
      running: { color: 'processing', icon: <PlayCircleOutlined /> },
      success: { color: 'success', icon: <CheckCircleOutlined /> },
      failed: { color: 'error', icon: <CloseCircleOutlined /> },
      paused: { color: 'warning', icon: <PauseCircleOutlined /> },
      cancelled: { color: 'default', icon: <StopOutlined /> },
    };

    const config = statusConfig[status];
    return (
      <Tag color={config.color} icon={config.icon}>
        {ExecutionStatusLabels[status]}
      </Tag>
    );
  };

  /**
   * 格式化执行时间
   */
  const formatExecutionTime = (timeMs?: number) => {
    if (!timeMs) return '-';
    
    const seconds = Math.floor(timeMs / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    
    if (hours > 0) {
      return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
    } else if (minutes > 0) {
      return `${minutes}m ${seconds % 60}s`;
    } else {
      return `${seconds}s`;
    }
  };

  /**
   * 格式化数据量
   */
  const formatDataSize = (records: number) => {
    if (records >= 1000000) {
      return `${(records / 1000000).toFixed(1)}M`;
    } else if (records >= 1000) {
      return `${(records / 1000).toFixed(1)}K`;
    } else {
      return records.toString();
    }
  };

  // 表格列定义
  const columns: TableColumnsType<SyncExecution> = [
    {
      title: '执行ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '任务ID',
      dataIndex: 'task_id',
      key: 'task_id',
      width: 80,
    },
    {
      title: '执行类型',
      dataIndex: 'execution_type',
      key: 'execution_type',
      width: 100,
      render: (type: ExecutionType) => (
        <Tag color={type === ExecutionType.MANUAL ? 'blue' : 'green'}>
          {ExecutionTypeLabels[type]}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: ExecutionStatus) => getExecutionStatusTag(status),
    },
    {
      title: '进度',
      key: 'progress',
      width: 200,
      render: (_, record: SyncExecution) => (
        <div>
          <Progress
            percent={record.progress_percentage}
            size="small"
            status={
              record.status === ExecutionStatus.FAILED ? 'exception' :
              record.status === ExecutionStatus.SUCCESS ? 'success' : 'active'
            }
          />
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {formatDataSize(record.processed_records)} / {formatDataSize(record.total_records)}
          </Text>
        </div>
      ),
    },
    {
      title: '成功/失败',
      key: 'records',
      width: 120,
      render: (_, record: SyncExecution) => (
        <Space direction="vertical" size={0}>
          <Text style={{ color: '#52c41a', fontSize: '12px' }}>
            成功: {formatDataSize(record.success_records)}
          </Text>
          <Text style={{ color: '#ff4d4f', fontSize: '12px' }}>
            失败: {formatDataSize(record.failed_records)}
          </Text>
        </Space>
      ),
    },
    {
      title: '执行时间',
      key: 'execution_time',
      width: 120,
      render: (_, record: SyncExecution) => (
        <Space direction="vertical" size={0}>
          <Text style={{ fontSize: '12px' }}>
            {formatExecutionTime(record.execution_time_ms)}
          </Text>
          {record.started_at && (
            <Text type="secondary" style={{ fontSize: '11px' }}>
              {new Date(record.started_at).toLocaleString()}
            </Text>
          )}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 160,
      fixed: 'right',
      render: (_, record: SyncExecution) => (
        <Space size="small">
          <PermissionGuard permission="sync:execution:view">
            <Tooltip title="查看日志">
              <Button
                type="text"
                size="small"
                icon={<EyeOutlined />}
                onClick={() => handleViewLogs(record)}
              />
            </Tooltip>
          </PermissionGuard>

          {/* 下载CSV文件按钮 - 只有成功执行且目标类型为CSV时才显示，Doris不显示 */}
          {record.status === ExecutionStatus.SUCCESS &&
           record.task?.target_datasource?.db_type !== 'DORIS' && (
            <PermissionGuard permission="sync:execution:view">
              <Tooltip title="下载CSV文件">
                <Button
                  type="text"
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownloadCSV(record)}
                />
              </Tooltip>
            </PermissionGuard>
          )}

          {record.status === ExecutionStatus.RUNNING && (
            <PermissionGuard permission="sync:execution:control">
              <Tooltip title="暂停">
                <Button
                  type="text"
                  size="small"
                  icon={<PauseCircleOutlined />}
                  onClick={() => handlePauseExecution(record)}
                />
              </Tooltip>
            </PermissionGuard>
          )}

          {record.status === ExecutionStatus.PAUSED && (
            <PermissionGuard permission="sync:execution:control">
              <Tooltip title="恢复">
                <Button
                  type="text"
                  size="small"
                  icon={<PlayCircleOutlined />}
                  onClick={() => handleResumeExecution(record)}
                />
              </Tooltip>
            </PermissionGuard>
          )}

          {(record.status === ExecutionStatus.RUNNING || record.status === ExecutionStatus.PAUSED) && (
            <PermissionGuard permission="sync:execution:control">
              <Tooltip title="取消">
                <Button
                  type="text"
                  size="small"
                  danger
                  icon={<StopOutlined />}
                  onClick={() => handleCancelExecution(record)}
                />
              </Tooltip>
            </PermissionGuard>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space wrap>
              <Input
                placeholder="任务ID"
                allowClear
                style={{ width: 120 }}
                value={selectedTaskId}
                onChange={(e) => handleFilterChange('taskId', e.target.value ? Number(e.target.value) : undefined)}
              />

              <Select
                placeholder="执行状态"
                allowClear
                style={{ width: 120 }}
                value={selectedStatus}
                onChange={(value) => handleFilterChange('status', value)}
              >
                {Object.entries(ExecutionStatusLabels).map(([key, label]) => (
                  <Option key={key} value={key}>{label}</Option>
                ))}
              </Select>
            </Space>
          </Col>

          <Col>
            <Space>
              <Button
                icon={<ReloadOutlined />}
                onClick={() => fetchExecutions(true)}
                loading={loading}
              >
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 数据表格 */}
      <Card>
        <Table<SyncExecution>
          columns={columns}
          dataSource={executions}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
          size="middle"
        />
      </Card>

      {/* 日志查看模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            执行日志 - ID: {selectedExecution?.id}
          </Space>
        }
        open={isLogsModalVisible}
        onCancel={closeLogsModal}
        footer={[
          <Button key="close" onClick={closeLogsModal}>
            关闭
          </Button>
        ]}
        width={1200}
        destroyOnClose
      >
        {selectedExecution && (
          <div>
            {/* 执行详情 */}
            <Card size="small" style={{ marginBottom: 16 }}>
              <Descriptions column={3} size="small">
                <Descriptions.Item label="执行状态">
                  {getExecutionStatusTag(selectedExecution.status)}
                </Descriptions.Item>
                <Descriptions.Item label="进度">
                  <Progress
                    percent={selectedExecution.progress_percentage}
                    size="small"
                    style={{ width: 150 }}
                  />
                </Descriptions.Item>
                <Descriptions.Item label="执行时间">
                  {formatExecutionTime(selectedExecution.execution_time_ms)}
                </Descriptions.Item>
                <Descriptions.Item label="总记录数">
                  {formatDataSize(selectedExecution.total_records)}
                </Descriptions.Item>
                <Descriptions.Item label="成功记录">
                  <Text style={{ color: '#52c41a' }}>
                    {formatDataSize(selectedExecution.success_records)}
                  </Text>
                </Descriptions.Item>
                <Descriptions.Item label="失败记录">
                  <Text style={{ color: '#ff4d4f' }}>
                    {formatDataSize(selectedExecution.failed_records)}
                  </Text>
                </Descriptions.Item>
              </Descriptions>

              {selectedExecution.error_message && (
                <Alert
                  message="执行错误"
                  description={selectedExecution.error_message}
                  type="error"
                  showIcon
                  style={{ marginTop: 16 }}
                />
              )}
            </Card>

            {/* 日志列表 */}
            <Card size="small" title="执行日志" loading={logsLoading}>
              {logs.length > 0 ? (
                <Timeline
                  mode="left"
                  items={logs.map(log => ({
                    color: log.log_level === 'ERROR' ? 'red' : 
                           log.log_level === 'WARNING' ? 'orange' : 'blue',
                    children: (
                      <div>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <Tag color={
                            log.log_level === 'ERROR' ? 'error' :
                            log.log_level === 'WARNING' ? 'warning' :
                            log.log_level === 'INFO' ? 'processing' : 'default'
                          }>
                            {LogLevelLabels[log.log_level]}
                          </Tag>
                          {log.batch_number && (
                            <Tag color="purple">批次 {log.batch_number}</Tag>
                          )}
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            {new Date(log.created_at).toLocaleString()}
                          </Text>
                        </div>
                        <div style={{ marginTop: 4 }}>
                          <Text>{log.log_message}</Text>
                        </div>
                        {log.log_details && (
                          <div style={{ marginTop: 4 }}>
                            <Text type="secondary" style={{ fontSize: '12px' }}>
                              {JSON.stringify(log.log_details, null, 2)}
                            </Text>
                          </div>
                        )}
                      </div>
                    )
                  }))}
                />
              ) : (
                <Alert
                  message="暂无日志"
                  description="该执行记录暂无日志信息"
                  type="info"
                  showIcon
                />
              )}
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default SyncExecutionMonitor;
